<?php

/**
 * This is the model class for table "{{article}}".
 *
 * The followings are the available columns in table '{{article}}':
 * @property integer $id
 * @property integer $mid
 * @property string $title
 * @property string $content
 * @property string $description
 * @property integer $rating
 * @property string $image
 * @property string $create_time
 * @property string $update_time
 * @property integer $status
 * @property integer $category_id
 * @property string $tags
 * @property integer $create_user_id
 * @property integer $update_user_id
 *
 * The followings are the available model relations:
 * @property Category $category
 * @property User $createUser
 * @property User $updateUser
 * @property Comment[] $comments
 * @property Rating[] $ratings
 */
class Article extends ArticleActiveRecord
{
    public $imagefile;
    public $iconsPath = '/';

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{article}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title, content, description, category_id, mid, tags', 'required'),
			array('rating, mid, status, category_id, create_user_id, update_user_id', 'numerical', 'integerOnly'=>true),
			array('title, image', 'length', 'max'=>255),
			array('content', 'length', 'min'=>100),
			array('description', 'length', 'min'=>10,'max'=>500),
			array('image', 'file','allowEmpty'=>true,'maxSize'=>8300000,'minSize'=>50,'types'=>'jpg,jpeg,png,gif'),
			array('create_time, update_time', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, title, content, description, rating, image, create_time, update_time, status, category_id, tags, create_user_id, update_user_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'categories' => array(self::BELONGS_TO, 'Category', 'category_id'),
			'parentMenu' => array(self::BELONGS_TO, 'Menu', 'mid'),
			'createUser' => array(self::BELONGS_TO, 'User', 'create_user_id'),
			'updateUser' => array(self::BELONGS_TO, 'User', 'update_user_id'),
			'comments' => array(self::HAS_MANY, 'Comment', 'article_id'),
			'ratings' => array(self::HAS_MANY, 'Rating', 'article_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'mid' => Yii::t('ArticleModule.base','Parent item'),
			'title' => Yii::t('ArticleModule.base','Title'),
			'content' => Yii::t('ArticleModule.base','Content'),
			'description' => Yii::t('ArticleModule.base','Description'),
			'rating' => Yii::t('ArticleModule.base','Rating'),
			'image' => Yii::t('ArticleModule.base','Image'),
			'create_time' => Yii::t('ArticleModule.base','Create Time'),
			'update_time' => Yii::t('ArticleModule.base','Update Time'),
			'status' => Yii::t('ArticleModule.base','Status'),
			'category_id' => Yii::t('ArticleModule.base','Category'),
			'tags' => Yii::t('ArticleModule.base','Tags'),
			'create_user_id' => Yii::t('ArticleModule.base','Create User'),
			'update_user_id' => Yii::t('ArticleModule.base','Update User'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('mid',$this->mid);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('content',$this->content,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('rating',$this->rating);
		$criteria->compare('image',$this->image,true);
		$criteria->compare('create_time',$this->create_time,true);
		$criteria->compare('update_time',$this->update_time,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('category_id',$this->category_id);
		$criteria->compare('tags',$this->tags,true);
		$criteria->compare('create_user_id',$this->create_user_id);
		$criteria->compare('update_user_id',$this->update_user_id);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
            'pagination'=>array('pageSize'=>10)
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Article the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    //Ф-ия возвращяет картинку статьи
    public function getImageForGrid()
    {
        if(isset($this->image) && file_exists(Yii::getPathOfAlias('webroot').'/images/article/'.$this->id.'/'.$this->image))
        {
            return CHtml::link(CHtml::image('/images/article/'.$this->id.'/'.$this->image,$this->image,array('class'=>'img-mini','data-toggle'=>'tooltip','title'=>$this->image)),Yii::app()->createUrl('/images/article/'.$this->id.'/'.$this->image),array('class'=>'fancybox','rel'=>'group'));
        }
        return CHtml::image('/images/system/noimage.png','noimage.png',array('class'=>'img-mini','data-toggle'=>'tooltip','title'=>Yii::t('ArticleModule.base','No photo')));
    }

    //Возвращаем стату статьи
    public function getStatusOptions()
    {
        return array('0'=>Yii::t('ArticleModule.base','No'),'1'=>Yii::t('ArticleModule.base','Yes'));
    }

    //Возвращяем статус статьи
    public function getArticleStatus()
    {
        if($this->status == 0)
        {
            return CHtml::tag('span',array('class'=>'label label-danger'),Yii::t('ArticleModule.base','No'));
        }
        return CHtml::tag('span',array('class'=>'label label-success'),Yii::t('ArticleModule.base','Yes'));
    }

    /**
     * Возвращает по id данные админа создавший пользователя
     * @return CActiveRecord
     */
    public function getCreateUserIdOptions()
    {
        $user = User::model();
        $criteria = new CDbCriteria();
        $criteria->select = 'name,login,role';
        $userData = $user->findByAttributes(array('id'=>$this->create_user_id),$criteria);
        if($userData)
        {
            return $userData;
        }
        else
        {
            $userData = $this->findByAttributes(array('id'=>$this->id),$criteria);
            return $userData;
        }
    }

    /**
     * Возвращает по id данные админа обновивший пользователя
     * @return CActiveRecord
     */
    public function getUpdateUserIdOptions()
    {

        $user = User::model();
        $criteria = new CDbCriteria();
        $criteria->select = 'name,login,role';
        $userData = $user->findByAttributes(array('id'=>$this->update_user_id),$criteria);

        if($userData)
        {
            return $userData;
        }
        else
        {
            $userData = $this->findByAttributes(array('id'=>$this->id),$criteria);
            return $userData;
        }

    }

    //Форматируем дату и время создания
    public function getCreateDateTimeFormat()
    {
        return CHtml::tag('span',array('class'=>'label label-default','style'=>'line-height:2'),CLocale::getInstance(Yii::app()->getLocale()->id)->dateFormatter->formatDateTime(strtotime($this->create_time),"long","short"));
    }

    //Форматируем дату и время обновления
    public function getUpdateDateTimeFormat()
    {
        if($this->create_time === $this->update_time)
        {
            return CHtml::tag('span',array('class'=>'label label-info'),Yii::t('ArticleModule.base','Article has not yet been updated')); //Yii::t('Article.base','Article has not yet been updated.');
        }
        return CHtml::tag('span',array('class'=>'label label-primary'),CLocale::getInstance(Yii::app()->getLocale()->id)->dateFormatter->formatDateTime(strtotime($this->update_time),"long","short"));
    }

    //Возвращяем статус статьи
    public function getStatus()
    {
        switch($this->status){
            case 0:
                return CHtml::tag('span',array('class'=>'label label-danger'),Yii::t('ArticleModule.base','No'));break;
            case 1:
                return CHtml::tag('span',array('class'=>'label label-success'),Yii::t('ArticleModule.base','Yes'));break;
            default : return Yii::t('ArticleModule.base','Undefined');
        }
    }

    //Возвращяем рейтинг
    public function getRating()
    {
        if(!$this->rating)
        {
            return CHtml::tag('span',array('class'=>'label label-info'),Yii::t('ArticleModule.base','Not rated'));
        }
    }

    //Возвращяем данные пользователя, который обновил,если они существуют.
    public function getUpdateUserData()
    {
        if($this->update_user_id)
        {
            $data = array();
            $data = CHtml::tag('span',array('class'=>'text-info'),Yii::t('ArticleModule.base','Name')).': '.CHtml::tag('b',array(),$this->updateUser->name).' | ';
            $data .= CHtml::tag('span',array('class'=>'text-info'),Yii::t('ArticleModule.base','Login')).': '.CHtml::tag('b',array(),$this->updateUser->login).' | ';
            $data .= CHtml::tag('span',array('class'=>'text-info'),Yii::t('ArticleModule.base','Role')).': '.CHtml::tag('b',array(),$this->updateUser->role);
            return $data;
        }
        else
        {
            return CHtml::tag('span',array('class'=>'label label-info','style'=>'line-height:2'),Yii::t('ArticleModule.base','Has not been updated'));
        }
    }

    //Возвращяем данные пользователя, который обновил,если они существуют.
    public function getCreateUserData()
    {
        if($this->create_user_id)
        {
            $data = array();
            $data = CHtml::tag('span',array('class'=>'text-info'),Yii::t('ArticleModule.base','Name')).': '.CHtml::tag('b',array(),$this->createUser->name).' | ';
            $data .= CHtml::tag('span',array('class'=>'text-info'),Yii::t('ArticleModule.base','Login')).': '.CHtml::tag('b',array(),$this->createUser->login).' | ';
            $data .= CHtml::tag('span',array('class'=>'text-info'),Yii::t('ArticleModule.base','Role')).': '.CHtml::tag('b',array(),$this->createUser->role);
            return $data;
        }
        else
        {
            return Yii::t('ArticleModule.base','Undefined');
        }
    }

    //Возвращяем все доступные категории
    public function getCategories()
    {
        $categories = $this->model('Category')->findAll();
        $items = CHtml::listData($categories,'id','name');
        return $items;
    }

    //Отдаем все меню сайта
    public function getMenuOptions()
    {
       $menu = Menu::model()->findAll();
        return CHtml::listData($menu,'id','item_name');
    }

    //Отдаем статус статей в виде иконок
    public function getStatusIcon()
    {

        if($this->status)
        {
            return CHtml::image(Yii::app()->theme->baseUrl.'/assets/gridview/yes.png',Yii::t('ArticleModule.base','Published'),array('title'=>Yii::t('ArticleModule.base','Published')));
        }
        else
        {
            return CHtml::image(Yii::app()->theme->baseUrl.'/assets/gridview/no.png',Yii::t('ArticleModule.base','Not published'),array('title'=>Yii::t('ArticleModule.base','Not published')));
        }
    }

    //
    public function getCategoryName()
    {
        $this->categories->name;
    }
}